package com.xdf.whiteaccount.service.impl;

import com.xdf.whiteaccount.dao.SysUserMapper;
import com.xdf.whiteaccount.dto.SysUserDTO;
import com.xdf.whiteaccount.entity.*;
import com.xdf.whiteaccount.service.*;
import com.xdf.whiteaccount.service.base.BaseService;
import com.xdf.whiteaccount.utils.CustumDozerMapperUtil;
import com.xdf.whiteaccount.utils.Example;
import com.xdf.whiteaccount.vo.SysUserVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description : com.xdf.whiteaccount.service.impl(业务层实现类,该类为生成器自动生成).
 * @Author : 张柯
 * @Date : 2020-12-31 14:42:38
 */
@Service
public class SysUserServiceImpl extends BaseService implements SysUserService {
    @Autowired
    private SysUserMapper dao;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysUserRoleGroupService userRoleGroupService;
    @Autowired
    private CustumDozerMapperUtil utils;

    /**
     * @Describe 新增方法
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(SysUser record) throws Exception {
        return dao.insert(record);
    }

    /**
     * @Describe 选择新增
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSelective(SysUser record) throws Exception {
        return dao.insertSelective(record);
    }

    /**
     * 带有角色的新增方法
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSelective(SysUserVO record) throws Exception {
        SysUser sysUser = utils.transObject(record, SysUser.class);
        int result = dao.insertSelective(sysUser);
        String[] roleGroups = Optional.ofNullable(record).map(SysUserVO::getGroupId).orElse("").split(",");
        List<Integer> list = Stream.of(roleGroups)
                .filter(StringUtils::isNotEmpty)
                .distinct()
                .map(Integer::parseInt).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(list)) {
            userRoleGroupService.multiInsert(list.stream().map(x ->
                    SysUserRoleGroup.builder()
                            .sysRoleGroupId(x)
                            .sysUserId(sysUser.getId())
                            .build()).collect(Collectors.toList()));
        }
        return result;
    }

    /**
     * @Describe 批量新增
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int multiInsert(List<SysUser> list) throws Exception {
        return dao.multiInsert(list);
    }

    /**
     * @Describe 修改
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKey(SysUser record) throws Exception {
        return dao.updateByPrimaryKey(record);
    }

    /**
     * @Describe 选择修改
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKeySelective(SysUser record) throws Exception {
        return dao.updateByPrimaryKeySelective(record);
    }

    /**
     * 带角色组的修改方法
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKeySelective(SysUserVO record) throws Exception {
        SysUser sysUser = utils.transObject(record, SysUser.class);
        SysUser prev = dao.selectByPrimaryKey(sysUser.getId());
        //  校验用户
        Assert.notNull(prev, "用户不存在或者已删除！");
        sysUser.setCreateTime(prev.getCreateTime());
        sysUser.setOpenid(prev.getOpenid());
        //  修改用户
        int result = dao.updateByPrimaryKey(sysUser);
        //  修改角色组
        String[] roleGroups = Optional.ofNullable(record).map(SysUserVO::getGroupId).orElse("").split(",");
        List<Integer> list = Stream.of(roleGroups)
                .filter(StringUtils::isNotEmpty)
                .distinct()
                .map(Integer::parseInt).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(list)) {
            //  删除
            Set<Integer> oldGroups = Optional.ofNullable(
                    userRoleGroupService.listQuery(SysUserRoleGroup.builder().sysUserId(sysUser.getId()).build()))
                    .orElse(new ArrayList<>())
                    .stream().map(SysUserRoleGroup::getSysRoleGroupId)
                    .collect(Collectors.toSet());
            Set<Integer> listGroups = list.stream().collect(Collectors.toSet());
            List<Integer> deleteList = oldGroups.stream().filter(filter -> !listGroups.contains(filter)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(deleteList)) {
                userRoleGroupService.deleteByExample(new Example().andEq("sys_user_id", sysUser.getId()).andIn("sys_role_group_id", deleteList.toArray()));
            }
            //  新增
            userRoleGroupService.multiInsert(list.stream()
                    .filter(filter -> !oldGroups.contains(filter)).map(x ->
                            SysUserRoleGroup.builder()
                                    .sysRoleGroupId(x)
                                    .sysUserId(sysUser.getId())
                                    .build()).collect(Collectors.toList()));
        } else {
            userRoleGroupService.deleteByUserId(sysUser.getId());
        }
        return result;
    }

    /**
     * 无事务的修改方法
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int updateByPrimaryKeySelectiveWithoutTransactional(SysUser record) throws Exception {
        return dao.updateByPrimaryKeySelective(record);
    }

    /**
     * @Describe 修改
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(SysUser record) throws Exception {
        return dao.updateByPrimaryKey(record);
    }

    /**
     * @Describe 批量修改
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int multiUpdate(List<SysUser> list) throws Exception {
        return dao.multiUpdate(list);
    }

    /**
     * @Describe 根据主键查询
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    public SysUser selectByPrimaryKey(Integer id) throws Exception {
        return dao.selectByPrimaryKey(id);
    }

    /**
     * @Describe 根据主键删除
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByPrimaryKey(Integer id) throws Exception {
        return dao.deleteByPrimaryKey(id);
    }

    /**
     * @Describe 根据Entity查询
     * @author 张柯
     * @Date 2020-12-31 14:42:38
     */
    @Override
    public List<SysUser> listQuery(SysUser record) throws Exception {
        return dao.selectByParam(record);
    }

    /**
     * 查询
     *
     * @param setRowSize
     * @return
     */
    @Override
    public List<SysUser> listQueryByExample(Example setRowSize) {
        return dao.selectByExample(setRowSize);
    }

    /**
     * 根据登录用户登录账号获取
     *
     * @param loginName
     * @return
     * @throws Exception
     */
    @Override
    public SysUser selectByLoginName(String loginName) throws Exception {
        if (StringUtils.isEmpty(loginName)) return null;
        List<SysUser> list = dao.selectByParam(SysUser.builder().loginName(loginName).build());
        if (CollectionUtils.isEmpty(list)) return null;
        return list.stream().findFirst().get();
    }

    /**
     * 查询角色
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public List<SysRole> selectRolesByUserId(Integer id) throws Exception {
        Integer[] roleGroupId = Optional.ofNullable(userRoleGroupService.listQuery(SysUserRoleGroup.builder()
                .sysUserId(id)
                .build()))
                .orElse(new ArrayList<>())
                .stream().map(x -> x.getSysRoleGroupId()).distinct().toArray(Integer[]::new);
        List<SysRole> roleList = roleService.selectByRoleGroupId(roleGroupId);
        return roleList;
    }

    /**
     * 根据用户编号查询
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public List<SysPermission> selectPermissionByUserId(Integer id) throws Exception {
        List<SysRole> sysRoles = selectRolesByUserId(id);
        if (CollectionUtils.isEmpty(sysRoles)) return null;
        if (sysRoles.stream().filter(x -> x.getRoleAdminSign() != null && x.getRoleAdminSign()).count() > 0) {
            List<SysMenu> menuList = Optional.ofNullable(menuService.listQuery(SysMenu.builder().build())).orElse(new ArrayList<>());
            return menuList.stream().map(x ->
                    SysPermission.builder()
                            .sysMenuId(x.getId())
                            .sysShow(1)
                            .sysAdd(1).sysAudit(1)
                            .sysDelete(1).sysExport(1)
                            .sysModify(1).sysMoney(1)
                            .sysPrice(1).sysPrint(1)
                            .build()
            ).collect(Collectors.toList());
        }
        List<SysPermission> list = permissionService.queryRoleId(sysRoles.stream().map(x -> x.getId()).toArray(Integer[]::new));
        return list;
    }

    /**
     * 查询当前登录用户
     *
     * @return
     * @throws Exception
     */
    @Override
    public SysUserDTO selectCurrentLoginUser() throws Exception {
        Integer userId = getLoginUserId();
        SysUser sysUser = dao.selectByPrimaryKey(userId);
        return utils.transObject(sysUser, SysUserDTO.class);
    }

    /**
     * 计数
     *
     * @param example
     * @return
     */
    @Override
    public Long count(Example example) {
        return dao.countByExample(example);
    }

    /**
     * 报表显示
     *
     * @param state
     * @return
     * @throws Exception
     */
    @Override
    public List<SysUserVO> listQuery(Integer state) throws Exception {
        return dao.selectByState(state);
    }
}